/**
 * Definition for singly-linked list.
 */
struct ListNode {
    int val;
    ListNode *next;
    ListNode() : val(0), next(nullptr) {}
    ListNode(int x) : val(x), next(nullptr) {}
    ListNode(int x, ListNode *next) : val(x), next(next) {}
};


class Solution {
public:
    // Better: 迭代 + 头插法
    ListNode* reverseKGroup(ListNode* head, int k) {
        if (k == 1) return head;

        ListNode* dummy = new ListNode(-1);
        dummy->next = head;
        ListNode* prev = dummy;
        ListNode* curr, * next;

        // Calculate length
        int length = 0;
        curr = head;
        while (curr) {
            length++;
            curr = curr->next;
        }
        if (length == 1) return head;

        // Reverse each k group
        int n = length / k;  // number of groups
        for (int i=0; i<n; i++) {
            curr = prev->next;
            for (int j=0; j<k-1; j++) {
                next = curr->next;
                curr->next = next->next;
                next->next = prev->next;
                prev->next = next;
            }
            for (int j=0; j<k; j++) prev = prev->next;
        }
        
        return dummy->next;
    }


    // Recursive
    ListNode* reverseKGroupRecursive(ListNode* head, int k) {
        if (!head || !head->next) return head;
        if (k == 1) return head;
        ListNode* dummyHead = new ListNode(-1);
        dummyHead->next = head;
        // 确保还有有K个
        ListNode* prev = dummyHead, * kstop = dummyHead;
        for (int i=0; i<k; ++i) {
            if (!kstop->next) return head;
            kstop = kstop->next;
        }
        // 头插法
        ListNode* curr = prev->next;
        ListNode* next;
        for (int i=0; i<k-1; ++i) {
            next = curr->next;
            curr->next = next->next;
            next->next = prev->next;
            prev->next = next; 
        }
        curr->next = reverseKGroup(curr->next, k);
        return dummyHead->next;
    }
};
